﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using SlamDunk.CMS.BLL;
using SlamDunk.CMS.Model;
using SlamDunk.CMS.Model.FormatModel;
using SlamDunk.CMS.Model.ViewModel;
using SlamDunk.CMS.UI.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SlamDunk.CMS.Model.DataModel;

namespace SlamDunk.CMS.UI.Areas.Admin.Controllers
{
    /// <summary>
    /// 硕士分数线控制器
    /// </summary>
    public class MasterScoreLineController : BaseController
    {
        #region 00.实例化业务层对象
        /// <summary>
        /// ScoreLineBll只读私有字段
        /// </summary>
        private readonly MasterScoreLineBll MasterScoreLineBll = new MasterScoreLineBll();
        #endregion

        #region 01.加载视图
        /// <summary>
        /// 加载列表视图
        /// </summary>
        /// <returns>列表视图</returns>
        public ActionResult Index()
        {
            this.ViewBag.YearList = this.MasterScoreLineBll.GetAllYear();
            return this.View();
        }
        #endregion

        #region 02.加载列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>EasyUI要求的json格式数据</returns>
        public ActionResult List()
        {
            //1.获取EasyUI请求的数据
            int pageIndex = string.IsNullOrEmpty(this.Request["page"]) ? 1 : int.Parse(this.Request["page"]);
            int pageSize = string.IsNullOrEmpty(this.Request["rows"]) ? 10 : int.Parse(this.Request["rows"]);
            int year = string.IsNullOrEmpty(this.Request["year"]) ? 0 : int.Parse(this.Request["year"]);
            int category = string.IsNullOrEmpty(this.Request["category"]) ? 0 : int.Parse(this.Request["category"]);
            //2.根据请求查询数据并转换视图模型
            int pageCount, rowCount;
            List<MasterScoreLineView> list = this.MasterScoreLineBll.GetModelList(pageIndex, pageSize, out pageCount, out rowCount, year, category).Select(x => x.ToViewModel()).ToList();
            //封装EasyUI模型
            DataGridModel dgModel = new DataGridModel()
            {
                total = rowCount,
                rows = list
            };
            //返回数据
            return this.Json(dgModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 03.添加——加载视图
        /// <summary>
        /// 添加——加载视图
        /// </summary>
        /// <returns>添加视图</returns>
        public ActionResult Add()
        {
            return this.View();
        }
        #endregion

        #region 04.添加——提交添加
        /// <summary>
        /// 添加——提交添加
        /// </summary>
        /// <param name="model">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult AddConfirm(MasterScoreLineView model)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //1.转换数据模型
                MasterScoreLine dataModel = model.ToDataModel();
                //2.获取添加后的数据模型
                MasterScoreLine newModel = this.MasterScoreLineBll.Add(dataModel);
                //3.非空校验
                if (newModel != null)
                {
                    //生成静态页
                    this.CreateMasterScoreLinePage();
                    return OperateContext.Current.JsonModel(1, "添加成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "添加失败！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }
        }
        #endregion

        #region 05.删除单行
        /// <summary>
        /// 删除单行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSingle(int id)
        {
            //1.查询该实体是否存在
            MasterScoreLine model = this.MasterScoreLineBll.GetModel(id);
            if (model == null)
            {
                return OperateContext.Current.JsonModel(0, "该实体不存在！");
            }
            else //2.如果存在，则删除
            {
                if (this.MasterScoreLineBll.PhysicalDelete(id))
                {
                    //生成静态页
                    this.CreateMasterScoreLinePage();
                    return OperateContext.Current.JsonModel(1, "删除成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(2, "删除失败，请重试！");
                }
            }
        }
        #endregion

        #region 06.删除选中行
        /// <summary>
        /// 删除选中的所有行
        /// </summary>
        /// <param name="selectedIds">选中行的Id</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSelected(string selectedIds)
        {
            try                 //涉及多次类型转换等操作，应处理异常
            {
                //1.处理前台选中的所有要删除的实体Id信息
                List<int> idList = selectedIds.Split(',').Select(x => int.Parse(x)).ToList();
                //2.执行批量删除操作
                idList.ForEach(x => this.MasterScoreLineBll.PhysicalDelete(x));
                //生成静态页
                this.CreateMasterScoreLinePage();
                return OperateContext.Current.JsonModel(1, "删除成功！");
            }
            catch (Exception ex)
            {
                //写入日志

                //返回异常信息
                return OperateContext.Current.JsonModel(0, ex.Message);
            }
        }
        #endregion

        #region 07.修改—加载视图
        /// <summary>
        /// 加载要修改的行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>修改视图</returns>
        public ActionResult Edit(int id)
        {
            //1.根据给定主键查询数据模型并转化为视图模型
            MasterScoreLineView viewModel = this.MasterScoreLineBll.GetModel(id).ToViewModel();
            //2.返回视图 + 视图模型
            return this.View(viewModel);
        }
        #endregion

        #region 08.修改—提交修改
        /// <summary>
        /// 提交修改
        /// </summary>
        /// <param name="viewModel">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult EditConfirm(MasterScoreLineView viewModel)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //1.将用户提交的视图模型转换为数据模型
                MasterScoreLine model = viewModel.ToDataModel();
                //2.执行修改操作
                if (this.MasterScoreLineBll.Update(model))
                {
                    //生成静态页
                    this.CreateMasterScoreLinePage();
                    return OperateContext.Current.JsonModel(1, "修改成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "修改失败，请重试！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }
        }
        #endregion

        #region 09.前台搜索列表
        /// <summary>
        /// 前台搜索列表
        /// </summary>
        /// <returns>JsonModel</returns>
        [AllowAnonymous]
        public ActionResult SearchList()
        {
            //获取用户输入
            int pageIndex = string.IsNullOrEmpty(this.Request["pageIndex"]) ? 1 : int.Parse(this.Request["pageIndex"]);
            int pageSize = 20;
            int year = string.IsNullOrEmpty(this.Request["year"]) ? 0 : int.Parse(this.Request["year"]);
            int category = string.IsNullOrEmpty(this.Request["category"]) ? 0 : int.Parse(this.Request["category"]);

            //根据用户输入查询
            int pageCount, rowCount;
            List<MasterScoreLineView> list = this.MasterScoreLineBll.GetModelList(pageIndex, pageSize, out pageCount, out rowCount, year, category).Select(x => x.ToViewModel()).ToList();

            //构造分页实体对象
            PageModel<MasterScoreLineView> pageModel = new PageModel<MasterScoreLineView>()
            {
                Data = list,
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = pageCount,
                RowCount = rowCount,
            };

            return OperateContext.Current.JsonModel(pageModel, 1, "OK");
        }
        #endregion

        #region 10.导入Excel视图
        /// <summary>
        /// 导入Excel视图
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult LoadExcel()
        {
            return this.View();
        }
        #endregion

        #region 11.导入Excel提交
        /// <summary>
        /// 导入Excel处理
        /// </summary>
        /// <returns>导入结果</returns>
        public ActionResult LoadExcelConfrim()
        {
            //接收用户上传的文件
            HttpPostedFileBase excel = this.Request.Files[0];
            //判断文件是否为空并且格式正确
            if (excel != null && Path.GetExtension(excel.FileName) == ".xls")
            {
                string fileName = Path.GetFileName(excel.FileName);
                string excelPath = this.Server.MapPath(string.Format("/UploadFiles/{0}", fileName));
                excel.SaveAs(excelPath);
                //导入Excel至数据库
                int successCount = this.LoadExcelToDB(excelPath);
                //删除文件
                System.IO.File.Delete(excelPath);
                //重新生成静态页

                return this.Content(string.Format("<script>window.top.window.$.messager.alert('OK', '成功导入{0}条数据！');window.top.topHelper.closeComWindow();</script>", successCount));
            }
            else
            {
                //return OperateContext.Current.JsonModel(0, "你上传的Excel文件格式不正确，请重试！");
                return this.Content("<script>window.top.window.$.messager.alert('Error', '您上传的Excel文件格式不正确，请重试！');window.top.topHelper.closeComWindow();</script>");
            }
        }

        /// <summary>
        /// 导入Excel到数据库的方法
        /// </summary>
        /// <param name="excelPath">Excel路径</param>
        private int LoadExcelToDB(string excelPath)
        {
            //定义导入成功的记录条数
            int successCount = 0;
            try
            {
                //创建文件流
                using (FileStream fsRead = System.IO.File.OpenRead(excelPath))
                {
                    //创建工作薄
                    IWorkbook wk = new HSSFWorkbook(fsRead);
                    //读取第一张工作表
                    ISheet sheet = wk.GetSheetAt(0);
                    //读取sheet中除标题外的每一行
                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        //实例化分数线实体
                        MasterScoreLine model = new MasterScoreLine();
                        //读取每行
                        IRow row = sheet.GetRow(i);
                        //构造实体对象
                        model.Year = (int)row.GetCell(0).NumericCellValue;
                        model.Major = row.GetCell(1).StringCellValue.Trim();
                        model.Category = (int)row.GetCell(2).NumericCellValue;
                        model.SumScore = (int)row.GetCell(3).NumericCellValue;
                        model.PoliticsEnglish = (int)row.GetCell(4).NumericCellValue;
                        model.BusiCompre = (int)row.GetCell(5).NumericCellValue;
                        model.DelFlag = false;
                        model.AddTime = DateTime.Now;
                        //调用业务层执行添加操作
                        if (this.MasterScoreLineBll.Add(model) != null)
                        {
                            successCount++;
                        }
                    }
                    return successCount;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
